<template>
  <div class="app-container" v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="用户名" prop="name">
        <el-input v-model="name" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="roles">
        <el-input v-model="roles" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="form.oldPassword" type="password"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="form.newPassword" type="password"></el-input>
      </el-form-item>
      <center>
          <el-button type="primary" @click="onSubmit('form')">提交</el-button>
          <el-button type="primary"><router-link to="/">回首页</router-link></el-button>
      </center>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import md5 from 'js-md5'
export default {
  name: 'publishActive',
  data() {
    var validatePwd = (rule, value, callback) => {
      var pattern = /^\S{6,20}$/g
      if (value === '') {
        callback(new Error('请输新入密码'))
      } else if (!pattern.test(value)) {
        callback(new Error('请输入6-20个非空白字符'))
      } else {
        callback()
      }
    }
    return {
      form: {
        oldPassword: '',
        newPassword: ''
      },
      rules: {
        newPassword: [
          { required: true, validator: validatePwd, trigger: 'blur' }
        ],
        oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }]
      },
      loading: false
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'roles'
    ])
  },
  methods: {
    onSubmit(formName) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.oldPassword === this.form.newPassword) {
            this.$message.error('原密码和新密码相同')
            return
          }
          this.loading = true
          const param = {
            'username': this.name,
            'oldPassword': md5(this.form.oldPassword),
            'newPassword': md5(this.form.newPassword)
          }
          this.$store.dispatch('ChangePassword', param).then((response) => {
            this.loading = false
            // console.log(this)
            this.$router.push({ path: '/' })
            // this.$message.success('更新成功')
          }).catch(() => {
            this.loading = false
            // this.$message.error('更新失败')
          })
        } else {
          console.log('error')
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.line{
  text-align: center;
}
</style>

